package cn.wolfcode.trip.app.controller;


import cn.wolfcode.trip.base.domain.Region;
import cn.wolfcode.trip.base.domain.Strategy;
import cn.wolfcode.trip.base.query.StrategyQueryObject;
import cn.wolfcode.trip.base.service.IRegionService;
import cn.wolfcode.trip.base.service.IStrategyService;
import com.github.pagehelper.PageInfo;
import freemarker.template.Configuration;
import freemarker.template.Template;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.util.HashMap;
import java.util.List;

/**
 * 地区控制器
 */
@Controller
@RequestMapping("regions")
public class RegionController {

    @Autowired
    private IRegionService regionService;
    @Autowired
    IStrategyService strategyService;
    @Autowired
    ServletContext servletContext;

    @RequestMapping(method = RequestMethod.GET)
    @ResponseBody
    public List<Region> listAll(Integer state){

        return regionService.listAll(state);
    }

    /**
     * 根据地区id查询攻略(html)
     * produces指定的生产内容格式
     * @return
     */
    @RequestMapping(value = "/{placeId}/strategies",method = RequestMethod.GET,produces = "text/html;charset=utf-8")
    @ResponseBody
    public void queryStrategies(StrategyQueryObject qo, HttpServletResponse response) throws Exception {
        //查询全部攻略
        qo.setState(null);//不需要条件
        PageInfo all = strategyService.queryForList(qo);

        //查询推荐攻略
        qo.setState(Strategy.STATE_HOT);//推荐状态
        qo.setPageSize(0);//不分页
        PageInfo hot = strategyService.queryForList(qo);

        //使用freemarker渲染模板 注意是 freemarker.template.包
        Configuration configuration = new Configuration(Configuration.VERSION_2_3_28);
        //设置末班目录
        configuration.setDirectoryForTemplateLoading(new File(servletContext.getRealPath("/template")));
        //获取模板
        Template template = configuration.getTemplate("strategyTemplate.ftl", "utf-8");
        //数据
        HashMap<Object,Object> map=new HashMap<>();
        map.put("hot",hot);
        map.put("all",all);
        //渲染数据
        template.process(map,response.getWriter());
    }

    /**
     * 根据地区id查询攻略(json)
     * @return
     */
    @RequestMapping(value = "/{placeId}/strategies",method = RequestMethod.GET,produces = "application/json;charset=utf-8")
    @ResponseBody
    public PageInfo queryStrategiesJson(StrategyQueryObject qo)  {
        return strategyService.queryForList(qo);
    }
}

